package net.wanglu.www.zzz.utils;

import java.util.Properties;

import edu.stanford.nlp.ie.AbstractSequenceClassifier;
import edu.stanford.nlp.ie.crf.CRFClassifier;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.parser.lexparser.LexicalizedParser;
import edu.stanford.nlp.pipeline.DeterministicCorefAnnotator;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.process.CoreLabelTokenFactory;
import edu.stanford.nlp.process.PTBTokenizer;
import edu.stanford.nlp.process.TokenizerFactory;
import edu.stanford.nlp.trees.GrammaticalStructureFactory;
import edu.stanford.nlp.trees.PennTreebankLanguagePack;
import edu.stanford.nlp.trees.TreebankLanguagePack;

public class StanfordUtils {
	
	private static LexicalizedParser lp = null;
	public static LexicalizedParser getLexicalizedParser() throws Exception {
		if ( lp == null ) {
			lp = LexicalizedParser.loadModel("edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz",
				"-maxLength", "128", "-retainTmpSubcategories");			
		}

		return lp;
	}
	
	private static GrammaticalStructureFactory gsf = null;
	public static GrammaticalStructureFactory getGrammaticalStructureFactory() throws Exception {
		if ( gsf == null ) {
			TreebankLanguagePack tlp = new PennTreebankLanguagePack();
			gsf = tlp.grammaticalStructureFactory();			
		}

		return gsf;
	}
	
	private static AbstractSequenceClassifier<CoreLabel> classifier = null;
	public static AbstractSequenceClassifier<CoreLabel> getAbstractSequenceClassifier() throws Exception {
		if ( classifier == null ) {
			String serializedClassifier = "edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz";
			classifier = CRFClassifier.getClassifierNoExceptions(serializedClassifier);
		}
		return classifier;
	}
	
	private static TokenizerFactory<CoreLabel> tokenizerFactory = null;
	public static TokenizerFactory<CoreLabel> getTokenizerFactory() throws Exception {
		if ( tokenizerFactory == null ) {
		    tokenizerFactory = PTBTokenizer.factory(new CoreLabelTokenFactory(), "");
		}
		return tokenizerFactory;
	}
	
	private static StanfordCoreNLP stanfordCoreNLP = null;
	public static StanfordCoreNLP getStanfordCoreNLP() throws Exception {
		if ( stanfordCoreNLP == null) {
		    Properties props = new Properties();
		    props.put("annotators", "tokenize, ssplit, pos, lemma, ner");
		    stanfordCoreNLP = new StanfordCoreNLP(props);				
		}
		return stanfordCoreNLP;
	}
	
	private static DeterministicCorefAnnotator corefAnnotator = null;
	public static DeterministicCorefAnnotator getCorefAnnotator() throws Exception {
		if ( corefAnnotator == null) {
			corefAnnotator = new DeterministicCorefAnnotator(stanfordCoreNLP.getProperties());
		}
		return corefAnnotator;
	}
}
